<template>
	<view v-if="order" class="container">
		<view v-if="order" class="title">收费单号：{{order.orderSn}}</view>
		<view v-if="order" class="title">收费名称：{{order.title}}</view>
		<view v-if="order" class="title">单据状态：{{order.payStatus === 0 ?'未交':'已交'}}</view>
		<view style="margin-top: 30rpx;">
			<u-table>
				<u-tr>
					<u-th>收费项目</u-th>
<!-- 					<u-th>单位</u-th>
					<u-th>单价(元)</u-th>
					<u-th>数量</u-th> -->
					<u-th>金额(元)</u-th>
				</u-tr>
				<u-tr v-for="(item, index) in list" :key="index" class="tr">
					<u-td>{{item.productName}}</u-td>
<!-- 					<u-td>{{item.productUnit}}</u-td>
					<u-td>{{item.standardUnitAmount}}</u-td>
					<u-td>{{item.count}}</u-td> -->
					<u-td>{{item.practicalTotalAmount}}</u-td>
				</u-tr>
			</u-table>
		</view>
		
		<view class="total">
			<view>总额:</view>
			<view class="bal">
				¥{{order.totalAmount}}(元)
			</view>
		</view>
		
		<view class="balance" v-if="balance > 0">
			<view>余额:{{balance/100}}元</view>
			<u-checkbox-group>
				<u-checkbox v-model="checked" shape="circle">使用余额支付</u-checkbox>
			</u-checkbox-group>
		</view>
		
		<u-button v-if="order.payStatus === 0" class="action" @click="payClick">在线支付</u-button>
	</view>
</template>

<script>
	// #ifdef H5
	const jweixin = require('jweixin-module')
	// #endif
	import {
		mapState
	} from 'vuex';
	import { getWxPrepare, getOrder, getWxConfig, wxOrderCheck, getWallet } from '@/api/pay.js'
	export default {
		data() {
			return {
				list: [],
				order: null,
				wxReady: false,
				
				checked: false,
				balance: 0
			}
		},
		computed: {
			...mapState({
				parentInfo: state => state.user.parentInfo,
			}),
		},
		onLoad(options) {
			this.id = options.id;
			this.getInfo();
			this.getWalletInfo();
			// #ifdef H5
				jweixin.ready(function () {
					console.log('ready');
					this.wxReady = true;
				})
				this.initWxConfig();
			// #endif
		},
		onUnload() {
			this.cancelInterval()
		},
		methods: {
			getInfo() {
				getOrder({id: this.id}).then(res => {
					console.log(res);
					this.order = res.data;
					console.log(this.order);
					this.list = res.data.contract.contractProducts
				})
			},
			payClick() {
				console.log(this.parentInfo);
				// #ifdef APP
					const params = {
						// 'resourceType': '1',
						'resourceId': this.id,
					}
				// #endif
				// #ifdef H5
					const params = {
						// 'resourceType': '1',
						'resourceId': this.id,
						'openId': this.parentInfo.openidWp
					}
				// #endif
				if (this.checked) {
					params.useDeposit = this.balance
				}
				console.log(params)
				getWxPrepare(params).then(res => {
					console.log(res);
					// #ifdef APP
						this.appPay(res.data.wxPayResult);
					// #endif
					// #ifdef H5
						this.h5Pay(res.data);
					// #endif
				})
			},
			h5Pay(res) {
				this.cancelInterval();
				this.timer = setInterval(() => {
					this.orderCheck(res.outTradeNo)
				}, 1000 * 2);
				this.chooseWXPay(res.wxPayResult)
			},
			cancelInterval() {
				if (!this.$u.test.isEmpty(this.timer)) {
					clearInterval(this.timer)
					this.timer = null
				}
			},
			chooseWXPay(wxPayResult) {
				const that = this;
				uni.showLoading()
				jweixin.chooseWXPay({
					timestamp: wxPayResult.timeStamp,
					nonceStr: wxPayResult.nonceStr,
					package: wxPayResult.packageValue,
					signType: wxPayResult.signType,
					paySign: wxPayResult.paySign,
					// success: function (res) {
					// 	// 支付成功后的回调函数
					// 	console.log(res);
					// 	this.$u.toast('支付成功');
					// 	uni.$emit('paySuccess',{});
					// 	uni.navigateBack({})
					// },
					// fail:function(r){
					// 	this.$u.toast(r);
					// },
					success: function(res) {
						// 支付成功后的回调函数
						// alert("支付成功4:");
					},
					error: function() {
						// alert("支付失败3");
						that.cancelInterval()
						uni.hideLoading()
					},
					cancel: function() {
						that.cancelInterval()
						uni.hideLoading()
					},
					complete: function() {
						// alert("支付完成1");
					},
				});
			},
			appPay(res) {
				const orderInfo = {
					appid: res.appId,
					noncestr: res.nonceStr,
					package: res.packageValue,
					partnerid: res.partnerId,
					prepayid: res.prepayId,
					timestamp: res.timeStamp,
					sign: res.sign,
				}
				console.log(orderInfo);
				uni.requestPayment({
					provider: 'wxpay',
					orderInfo: orderInfo,
					success: function (res) {
						console.log('success:' + JSON.stringify(res));
						this.$u.toast('支付成功');
						uni.$emit('paySuccess',{});
						uni.navigateBack({})
					},
					fail: function (err) {
						console.log('fail:' + JSON.stringify(err));
						this.$u.toast(err);
					}
				});
			},
			
			initWxConfig() {
				getWxConfig(window.location.href).then(res => {
					console.log(res);
					if (res.code === '000000') {
						jweixin.config({
							debug: false,
							appId: res.data.appId,
							timestamp: res.data.timestamp,
							nonceStr: res.data.nonceStr,
							signature: res.data.signature,
							jsApiList: [
								'chooseWXPay',
							]
						})
					} else {
						this.$u.toast('微信支付参数获取失败:' + res.message);
					}
				})
			},
			
			orderCheck(outTradeNo) {
				wxOrderCheck(outTradeNo).then(res => {
					this.$u.toast('支付成功');
					setTimeout(function() {
						uni.$emit('paySuccess',{});
						uni.navigateBack({})
					}, 1000);
				})
			},
			
			getWalletInfo() {
				getWallet().then(res => {
					console.log(res)
					this.balance = res.data.balance
				})
			}
		}
	}
</script>

<style lang="scss">
	page{
		background-color: $app-page-bg-color;
	}
	.container{
		padding: 0 $app-page-padding;
		.title{
			font-size: $app-font-size-lg;
			color: $app-font-color;
			font-weight: bold;
			margin-top: 10rpx;
		}
		
		.tr{
			height: 60rpx;
		}
		
		.total{
			display: flex;
			flex-direction: row;
			justify-content: flex-end;
			margin-top: 50rpx;
			
			.bal{
				color: #DA473A;
			}
		}
		
		.balance{
			display: flex;
			flex-direction: row;
			justify-content: space-between;
			margin-top: 10rpx;
			align-content: center;
		}
	}
	
	.action{
		margin-top: 150rpx;
	}
</style>
